package com.sh.d1.gameserver.cmdhandler;

import com.sh.d1.gameserver.Broadcaster;
import com.sh.d1.gameserver.login.LoginService;
import com.sh.d1.gameserver.model.User;
import com.sh.d1.gameserver.model.UserManager;
import com.sh.d1.gameserver.msg.GameMsgProtocol;
import com.sh.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用户入场指令处理器
 */
public class UserEntryCmdHandler implements ICmdHandler<GameMsgProtocol.UserEntryCmd> {
    /**
     * 日志对象
     */
    static private final Logger LOGGER = LoggerFactory.getLogger(UserEntryCmdHandler.class);

    @Override
    public void handle(MyCmdHandlerContext ctx, GameMsgProtocol.UserEntryCmd cmd) {
        if (null == ctx ||
                null == cmd) {
            return;
        }

        // 先拿到用户 Id
        int userId = ctx.getFromUserId();

        if (userId <= 0) {
            return;
        }
        LoginService.getInstance().getLoginUser(userId, (userEntity) -> {
            LOGGER.info("获取已经登录的用户, userId={}", userId);
            // 新建用户并添加到管理器
            User newUser = new User();
            newUser.userId = userEntity.userId;
            newUser.userName = userEntity.userName;
            newUser.heroAvatar = userEntity.heroAvatar;
            newUser.currHp = 100;

            UserManager.add(newUser);

            GameMsgProtocol.UserEntryResult.Builder
                    resultBuilder = GameMsgProtocol.UserEntryResult.newBuilder();
            resultBuilder.setUserId(userId);
            resultBuilder.setUserName(userEntity.userName);
            resultBuilder.setHeroAvatar(userEntity.heroAvatar);

            // 构建结果并发送
            GameMsgProtocol.UserEntryResult newResult = resultBuilder.build();
            Broadcaster.broadcast(newResult);

            LoadStatistic.addUserId(ctx.getGatewayServerId(), userId);
            return null;

        });

    }
}
